
define(['template/mobile/edit','mobile/style','mobile/ani','mobile/otherSet','mobile/entity','mobile/particles','qrcode','wx','wx.tpl','wx.upload','wx.validator','wx.ajax','vendor/squire-raw'],function(tpl,styleCon,aniCon,otherSet,entity,particles,qrcode,wx){
	var currentPage = 0;
	var $cPage = null;
	var containerWidth,containerHeight;
	var focusEle;
	var sceneId;
	var $container;
	var globalSetting  = {};
	var windowParentId;
	var getUrl;
	var mobileEdit = {};
	var gSetData;
	var actInfo;
	
	function setCurrent(pageId,curlist){
		currentPage = pageId;
		$cPage = $('#Js-container #page'+pageId);
		$cPage.addClass('Js-curActive');
		if(curlist){
			curlist.addClass('active').siblings().removeClass('active');
		}else{
			$('.Js-pageList-item').removeClass('active').eq(pageId-1).addClass('active');
		}
	}
	function addPage(){
		var curPage = $("#Js-pageList li").length+1;
		$('#Js-container').append(wx.tpl(tpl.page,{pageId:'page'+curPage}));
		$('#Js-pageList').append(wx.tpl(tpl.pageitem,{pageId:curPage}));
		if(curPage == 1){
			$('.Js-pageList-item').eq(0).addClass('active');
		}
	}

	function switchPage(pageId,curlist){
		setCurrent(pageId,curlist);
		$('#Js-container').children().addClass('f-hide').removeClass('Js-curActive');
		$('#page'+pageId).css('z-index',2).removeClass('f-hide').addClass('Js-curActive');
	}

	function init(param){
    	param = wx.stringToJson(param);
		getUrl = frontWebUrl+"/activity/"+param.id+".html";
    	// getUrl = frontWebUrl+"/activity/"+param.id+".html";
		$('#window-frame-mobileedit').html(tpl.back+wx.tpl(tpl.fn,{url:getUrl})+tpl.container+tpl.setting+tpl.pagelist);
		addPage();
		setCurrent(1);
		fnEvent(param);
		entity.configSetting(param.id,addPage,function(info){
			actInfo = info;
			var settingData = $('#Js-container').data('setting')||{}
			globalSetting = settingData.setting || {};
			gSetData = globalSetting.gSet = globalSetting.gSet ||{};
			globalSetting.jscode = globalSetting.jscode || ''; // 添加默认值 chengrong
			windowParentId = param.parentId;
    		sceneId = param.id;
			$container = $('#Js-container');
			containerWidth = $container.width();
			containerHeight = $container.height();
			initPage(param);
		});
	}

    function initPage(param){
    	currentPage=0;

		$('#Js-pageList-add').click(addPage);
		$('#Js-pageList').delegate('.Js-pageList-item','click',function(){
			switchPage($(this).find('.Js-pageList-del').data('id'),$(this));
		}).delegate('.Js-pageList-del','click',function(e){
			e.stopPropagation();
			$('#page'+$(this).data('id')).remove();
			var index = $(this).parent().index();
			var prevList = $(this).parent().prev();
			var nextList = $(this).parent().next();
			$(this).parent().remove();
			var listLen = sortPageList();
			if(listLen < index+1){
				switchPage(prevList.find('.Js-pageList-del').data('id'),prevList);
			}else{
				switchPage(nextList.find('.Js-pageList-del').data('id'),nextList);
			}
		});
		 $("#Js-pageList").sortable({
		      	placeholder: "drag_highlight",
		      	axis: "y",
		      	opacity: 0.5,
		      	update:function(evt,ui){
		      		sortPageList();
		      	}
		});
	    // $("#Js-pageList").disableSelection();

		$(document).click(function(event){
			if($(event.target).hasClass('Js-stay') || $(event.target).parents('#Js-setting,.Js-comp-resize,.mobile-comppont').length) return;
			$('.Js-compont').draggable('enable').attr('contenteditable',false);
			$('.Js-comp-text').attr('contenteditable',false);
			$('.mobile-text-edit').removeClass('mobile-text-edit');
			$('#Js-text-edit').remove();
			$('.Js-comp-resize,#Js-setting,#Js-del').hide();
			// window.getSelection().removeAllRanges();
			clearInterval(timerId);
		});
	}
	function sortPageList(){
		var i=1;
		$('#Js-pageList').find('li').each(function(){
			$(this).find('span').text(i);
			$(this).find('a').text('第'+i+'页');
			i++;
		});
		return i-1;
	}
	function fnEvent(param){
		$('#Js-mobile-back').click(function(){
			Core.close(param.windowId);
			$('#desk').find('>ul>li:first').trigger('dblclick');
		});
		$('#Js-addText').click(function(event,textTpl,$page){
			var $text = $(wx.tpl(tpl.outborder,{type:0,compont:textTpl||tpl.text}));
			$($page||$cPage).append($text);
			$text.find('.mobile-comppont').data('info',{ani:[],type:0});
			bindEvent($text);
			return $text;
		});
		$('#Js-setting').delegate('>ul>li', 'click', function(event) {
			$(this).addClass('active').siblings('li').removeClass('active');
			$('#Js-styleContent,#Js-aniContent,#Js-otherContent').hide();
			$('#Js-'+$(this).data('flag')+'Content').show();
		}).delegate('.panel-heading','click', function () { 
			if($(this).next().hasClass('in')){//hide
				$(this).find('b').addClass('off');
			}else{//show
				$(this).find('b').removeClass('off');
			}
		});			
		wx.upload($('#Js-upload'));
		wx.upload($('#Js-bgUpload'));
		wx.upload($('#Js-micUpload'));
		$('#Js-upload').on('upload',function(event,data,$page){
			var imageTpl,$image,imgSrc;
			if(typeof data == 'string'){
				$image = $(wx.tpl(tpl.outborder,{type:1,compont:data}));
			} else {
				imageTpl = wx.tpl(tpl.image,{src:data.path});
				$image = $(wx.tpl(tpl.outborder,{type:1,compont:imageTpl}));
			}
			$image.find('.mobile-comppont').data('info',{ani:[],type:1});
			($page||$cPage).append($image);
			imgSrc = data.path||$image.find('img').attr('src');
			var ori_width = $image.find('img').width();
			if(imgSrc){
				wx.imgLoad(imgSrc,function(width,height){
					if(ori_width == 0 && width>200)
						$image.find('img').width(120);
					bindEvent($image);
				});
			}
			return $image;
		});

		$('#Js-bgUpload').on('upload',function(event,data){
			$cPage.css('background-image','url('+data.path+')');
		});
		$('#Js-micUpload').on('upload',function(event,data){
			if(data.status == 0){
				globalSetting.audio = data.path;
				wx.alert('上传成功');
			} else {
				wx.alert('上传失败');
			}
		});

		$('#Js-del').click(function(){
			var _this=this;
			wx.confirm('是否删除此元素',{fn:function(){
				$(_this).data('ele').remove();
			}})
		});

		$('#Js-preview').click(function(){
			require(['mobile/preview'],function(preview){
				preview(true);	
			});
		});

		$('#Js-save').click(function(){
			globalSetting.gSet = gSetData;
			$container.data('setting',globalSetting);
			entity.save(sceneId);
		});
		/*表单*/
		$('#Js-form').hover(function(){
			$('.formList').fadeIn('fast');
		},function(){
			$('.formList').fadeOut('fast');
		});
		//添加input
		$('#Js-addInput').click(function(event,inputTpl,$page){
			var $input = $(wx.tpl(tpl.outborder,{type:2,compont:inputTpl||tpl.input}));
			($page||$cPage).append($input);
			$input.find('.mobile-comppont').data('info',{ani:[],type:2});
			bindEvent($input);
			return $input;
		});
		//全局设置
		$('#Js-gSet').click(function(event){
			if(!globalSetting.gSet.shareInfo){
				gSetData.shareInfo = {
					'title':'',
					'descFriend':'',
					'titleCircleFriends':'',
					'link':'',
					'imgUrl':'',
					'isshare':true,
					'isgetUserInfo':false
				};
				gSetData.transEff = 'normal';
			}
			wx.pop(wx.tpl(tpl.gsetting,gSetData));
			resetActInfo();
			wx.upload($('#Js-uploadIcon'));

			$('#Js-gSetcon').delegate('.Js-tabs li','click',function(){
				$(this).addClass('active').siblings('li').removeClass('active');
				$('#Js-set-base,#Js-set-share,#Js-set-trans').hide();
				$('#Js-set-'+$(this).data('flag')).show();
			});
			$('#Js-set-trans label').change(function(){
				gSetData.transEff = $(this).find('input').val();
			});
			$('#Js-save-shareinfo').off('click').on('click',function(){
				gSetData.shareInfo = {};
				$('#Js-set-share input').each(function(){
					if($(this).attr('name') == "isshare" || $(this).attr('name') == "isgetUserInfo"){
						gSetData.shareInfo[$(this).attr('name')] = $(this).is(':checked');
					}else{
						gSetData.shareInfo[$(this).attr('name')] = $(this).val();
					}
				});
				$.succ('保存成功');
			});
			$('#Js-uploadIcon').off('upload').on('upload',function(event,data){
				if(data.status == 0){
					$('.Js-actIcon').val(data.path);
				}else{
					wx.alert('上传失败');
				}
			});
		});

		//添加脚本
		$('#Js-addCode').click(function(event){
			globalSetting.jscode = globalSetting.jscode.replace(/</g,'&lt;').replace(/>/g,'&gt;');
			wx.pop(wx.tpl(tpl.jscode,globalSetting));
			var editor;
			require(['common'],function(common){
				common.createAce('Js-mobile-code',function(e){
					editor = e;
				});
			});
			$('.Js-saveCode').off('click').click(function(){
				globalSetting.jscode = editor.getValue().replace(/&lt;/g,'<').replace(/&gt;/g,'>');
				$('.Js-dialog-close').trigger('click');
			});
		});
		//添加按钮
		$('#Js-addSubBtn').click(function(event,buttonTpl,$page){
			var $btn = $(wx.tpl(tpl.outborder,{type:3,compont:buttonTpl||tpl.button}));
			($page||$cPage).append($btn);
			$btn.find('.mobile-comppont').data('info',{ani:[],type:3});
			bindEvent($btn);
			return $btn;
		});

		$('#Js-qrcode').hover(function(){
			$(this).find('.Js-ercode').fadeIn('fast');
			if($(this).find('.Js-ercode canvas').length == 0){
				var qrcode = new QRCode($(this).find('.Js-ercode')[0], {
		            width : 135,
		            height : 135
		        });
		        qrcode.makeCode(getUrl);
			}
		},function(){
				$(this).find('.Js-ercode').fadeOut('fast');
		});
	}
	function resetActInfo(){
		wx.validator();
		$('.Js-actname').val(actInfo.name);
		$('.Js-actdesc').val(actInfo.description);
		$('.Js-actid').val(actInfo.id);
		$('form[name="actInfoSet"]').off('validator').on('validator',function(evt,data){
			if(data.status==0){
				actInfo.name = $('.Js-actname').val();
				actInfo.description = $('.Js-actdesc').val();
				$.succ('修改成功');
			}else{
				$.fail('修改失败');
			}
			
		});
	}
    function initSetting($ele){
		$('#Js-setting').empty().append(tpl.settingcontent);
		$('#Js-setting').find('#Js-styleContent').html(wx.tpl(tpl.settingstyle,$ele.data('info')));
		$('#Js-setting').find('#Js-ani').html(wx.tpl(tpl.settingani,$ele.data('info')));
		$('#Js-setting').find('#Js-otherContent').html(wx.tpl(tpl.otherSet,$ele.data('info')));

		$('#Js-setting').delegate('input[type="range"]','mousemove',function(){
			$(this).next().val($(this).val());
			$(this).parent().triggerHandler('rangeChange',$(this).val());

		});

		$('#Js-setting').delegate('input[type="number"]','input',function(){
			if($(this).prev().attr('type')!='range') return;
			var range = $(this).prev(),min = range.attr('min')|0,max = range.attr('max')|0;
			if($(this).val()>max)
				$(this).val(max);
			else if($(this).val()<min)
				$(this).val(min);
			$(this).prev().val($(this).val());
			$(this).parent().triggerHandler('rangeChange',$(this).val());
		});

		styleCon($ele);
		aniCon($ele);
		otherSet($ele);
		
    }

    //var aaa;

    var timerId;

    function bindEvent($ele){
    	$ele.hover(function(){
    		$ele.find('#inputDrag').addClass('inputdrag');
    	},function(){
    		$ele.find('#inputDrag').removeClass('inputdrag');
    	});
    	if($($ele[0]).length)
    	$($ele[0]).draggable({
		  	drag: function( event, ui ) {
		  		/*var e = 0;
		  		var tg = $(event.target);
		  		console.log(tg.width()+'------'+tg.height());
		  		var h = tg.offset();
		  		var w = tg.width();
		  		var h = tg.height();
		  		var o = tg.position();
		  		var trans = tg.get(0).style.transform || deg.get(0).style.webkitTransform || 0;
		  		var deg = trans && trans.replace("rotateZ(", "").replace("deg)", "");
		  		deg = deg && parseFloat(deg),deg >= 90 && 180 > deg && (deg = 180 - deg), deg >= 180 && 270 > deg && (deg = 270 - deg), deg >= 270 && 360 > deg && (deg = 360 - deg),e = 2 * deg * Math.PI / 360;
		  		var m = 0 == e ? h : (w / 2 + h / 2 / Math.tan(e)) * Math.sin(e) * 2,
		  			n = 0 == e ? w : (w / 2 + h / 2 / Math.tan(Math.PI / 2 - e)) * Math.sin(Math.PI / 2 - e) * 2;
		  		var i = {
		  			 height: m,
                     width: n
		  		};
		  		console.log('i==',i);
		  		var l = {
                            width: containerWidth,
                            height: containerHeight
                        };
                 var g = ui.position;
*/
	
		  		if(ui.position.left<0)
		  			ui.position.left = 0;
		  		else if(ui.position.left+$(event.target).width() > containerWidth-0)
		  			ui.position.left = containerWidth - $(event.target).width()-0;
		  		if(ui.position.top<0)
		  			ui.position.top = 0;
		  		else if(ui.position.top+$(event.target).height()>containerHeight-0)
		  			ui.position.top = containerHeight - $(event.target).height()-0;

		  		ui.helper.css({
					opacity:0.35
				});

				$('#Js-del').hide();
		  	},
		    stop:function(event,ui){
		    	ui.helper.css({
		  			opacity:1
		  		})
		   }
		});
		$ele.dblclick(function(){
			if($('#Js-text-edit').length || $ele.find('#inputDrag').length || $ele.find('.Js-comp-img').length) return;
			$(this).draggable( "disable" );
			$(this).find('.Js-comp-text').attr('contenteditable',true).addClass('mobile-text-edit');
			$('#Js-container').append(wx.tpl(tpl.textedit,{top:($(this).position().top-50)+'px',color:tpl.colorselect}));
			bingTextEditEvent($(this));
		}).click(function(event) {
			if(focusEle != $ele)
				$('.Js-comp-resize',focusEle).hide();
			focusEle = $ele;
			$('.Js-comp-resize',$ele).show();
			$('#Js-setting').show();
			initSetting($(this).find('.mobile-comppont'));
			$('#Js-del').css({
				left:$('#Js-container').offset().left-25,
				top:$ele.offset().top-30
			}).show().data('ele',$ele);
			if($ele.find('input').length){
				$('.Js-pholder').show();
			}else{
				$('.Js-pholder').hide();
			}
		});

		var dom = $ele;//u
		var mobcomp = dom.find('.mobile-comppont');
		var type = dom.data('type');
		var dom_w = mobcomp.outerWidth(true);//h
		var dom_h = dom_h = mobcomp.outerHeight(true);
		$ele.width(dom_w).height(dom_h);
		var dom_left = parseFloat(dom.css("left"));//j 
		var dom_top = parseFloat(dom.css("top"));//k
		var posY = posX = 0, p,q;
		var direc = "";
		var deltaX = deltaY = 0;
		var min_w = parseFloat(dom.css("min-width") || 50);//w
		var min_h = parseFloat(dom.css("min-height") || 30);//x
		var cur_y = dom_top + dom_h;//m
		var cur_x = dom_left +dom_w;//l
		var absY = 486 - dom_top;//n
		var absX = 320 - dom_left;//o
		var w_h = dom_w / dom_h;//r

		var setDeg = wx.throttle(function(deg){
			var info = $ele.find('.mobile-comppont').data('info');
				info.rotate = deg;
				$('#Js-setting-rotate').val(deg).next().val(deg);
			},200);


		$('.bar-radius',$ele).on("mousedown",function(event) {
				$('.Js-compont').draggable("disable");
				posY = event.pageY;
				posX = event.pageX;
				cur_x = parseFloat(dom.css("left")) + mobcomp.outerWidth(true);//j 
				cur_y = parseFloat(dom.css("top")) + mobcomp.outerHeight(true);//k
				direc = $(event.target).attr("direc");
				$('body').css({
					"user-select": "none"
				});
			$(document).mousemove(function(event){
				deltaX = event.pageX - posX;
				deltaY = event.pageY - posY;
					switch(direc){
						case "n-resize":
							if (dom_h - deltaY <= min_h) break;
								if (dom_h - deltaY >= cur_y) {
									dom.css({
										top: 0,
										height: cur_y
									});
									break;
							}
							dom.css({
								top: dom_top + deltaY,
								height: dom_h - deltaY
							});
						break;
						case "s-resize":
							if (dom_h + deltaY >= absY) {
								dom.css("height", absY);
								break;
							}
							dom.css("height", dom_h + deltaY);
						break;
						case "w-resize":
							if (dom_w - deltaX <= min_w) break;
								if (dom_w - deltaX >= cur_x) {
									dom.css({
										left: 0,
										width: cur_x
									});
									break;
							}
							dom.css({
								left: dom_left + deltaX,
								width: dom_w - deltaX
							});
						break;
						case "e-resize":
							if (dom_w + deltaX >= absX) {
								dom.css("width", absX);
								break;
							}
							dom.css("width", dom_w + deltaX);
						break;
						case "ne-resize":
							if (p = dom_h - deltaY*0.75, q = p * w_h, min_w >= q || min_h >= p || q >= absY || p >= cur_y) break;
								dom.css({
									top: cur_y - p,
									height: p,
									width: q
								});
						break;
						case "nw-resize":
							if (p = dom_h - deltaY*0.75, q = p * w_h, min_w >= q || min_h >= p || q >= cur_x || p >= cur_x) break;
								dom.css({
									top: cur_y - p,
									left: cur_x - q,
									height: p,
									width: q
								});
						break;
						case "se-resize":
						if (p = dom_h + deltaY*0.75, q = p * w_h, min_w >= q || min_h >= p || q >= absY || p >= absX) break;
								dom.css({
									height: p,
									width: q
								});
						break;
						case "sw-resize":
						if (p = dom_h + deltaY*0.75, q = p * w_h, min_w >= q || min_h >= p || q >= cur_x || p >= absX) break;
								dom.css({
									left: cur_x - q,
									height: p,
									width: q
								});
						break;
						case "rotate":
						var dom_par = dom.parent();
						var g = {
							x: parseFloat(dom.css("left")) + dom_par.offset().left + dom.width() / 2,
							y: parseFloat(dom.css("top")) + dom_par.offset().top + dom.height() / 2
						};
							
						var c = event.pageX - g.x,
							e = event.pageY - g.y,
							h = Math.abs(c / e);
						f = Math.atan(h) / (2 * Math.PI) * 360;
						c > 0 && 0 > e ? f = 360 + f : c > 0 && e > 0 ? f = 180 - f : 0 > c && e > 0 ? f = 180 + f : 0 > c && 0 > e && (f = 360 - f);
						if(f > 360)
							f -= 360;
						f = f|0;
						dom.css({
							transform: "rotateZ(" + f + "deg)"
						});

						setDeg(f);
						break;

						default:
						break;

					}
					
					if(type == '1'){
						$ele.find('img').width($ele.width()-5);
						$ele.find('img').height($ele.height()-5);
					}else if(type == '2'){
						$ele.find('input').width($ele.width()-10);
						$ele.find('input').height($ele.height()-10);
					}else{
						$ele.find('.comp_paragraph').width($ele.width()-10);
						$ele.find('.comp_paragraph').height($ele.height()-10);
					}
				}).mouseup(function(event){
					$('.Js-compont').draggable("enable");
					dom_h = dom.height();
					dom_w = dom.width();
					dom_left = parseFloat(dom.css("left"));//j 
					dom_top = parseFloat(dom.css("top"));//k
					cur_y = dom_top + dom_h;//m
					cur_x = dom_left +dom_w;//l
					absY = 486 - dom_top;//n
					absX = 320 - dom_left;//o
					w_h = dom_w/dom_h;
					$(document).unbind('mousemove').unbind('mouseup');
			});
		});
    }

	var editor;
    function bingTextEditEvent($ele){
    	$('.dropdown-toggle').click(function(){
    		$('.dropdown-menu').hide();
    		$(this).next('.dropdown-menu').show();
    	});
		editor = new Squire( $ele[0]);
		$('#Js-font-size').delegate('li','click',function(){
			editor.setFontSize($(this).text());
    		$('.dropdown-menu').hide();
		});

		$('#Js-font-color').delegate(  'a','click',function(){
			editor.setTextColour($(this).attr('data-edit'));
    		$('.dropdown-menu').hide();
		});
		
		$('#Js-back-color').delegate('a','click',function(){
			editor.setHighlightColour($(this).attr('data-edit'));
    		$('.dropdown-menu').hide();
		});

		$('#Js-text-bold').click(function(){
			if(editor.hasFormat('b'))
				editor.removeBold();
			else
				editor.bold();
    		$('.dropdown-menu').hide();
		});

		$('#Js-link').click(function(event) {
			if(editor.hasFormat('a')){
    			$(this).next('.dropdown-menu').hide();
				editor.removeLink();
			}else{
				initFrame();
			}
		});
	}

	function initFrame(){
		var frame = $('#Js-linkIframe')[0];
		var doc = frame.contentDocument;
		var style = doc.createElement( 'style' );
		style.type = 'text/css';
		style.textContent = 'body{margin:0;padding:0;overflow: hidden;}input[type="checkbox"]:focus{border:none;}label{font-size:12px;color:#ccc;}input[type="text"]{margin-left:4px;width:75%;display: block;float:left;}span{cursor:pointer;display:block;float:left;width:30px;height:20px;line-height:20px;margin-left:2px;border:1px solid #ccc;background-color:#e2e2e2;text-align:center;}';
		var script = doc.createElement( 'script' );
		script.type = 'text/javascript';
		script.textContent = 'function getValue(){window.parent.linkValue(document.querySelector("#Js-link").value,document.querySelector("#Js-cb").checked)}';

		doc.querySelector( 'head' ).appendChild( style );
		doc.querySelector( 'head' ).appendChild( script );
		$(doc.body).html('<input id="Js-link" type="text" placeholder="输入网址..."><span onclick="getValue();">ok</span><label><input id="Js-cb" type="checkbox">打开新窗口</label');
	}

	window.linkValue = function(v,c){
		if(!v) return;
		editor.makeLink(v,{'target':c?'_blank':'_self'});
		$('#Js-linkIframe').parent().hide();
	};
	mobileEdit.init = init;
    return mobileEdit;
});